﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CIT.WMS.TranseferRM
{
    public partial class FrmMove : Form
    {
        public FrmMove()
        {
            InitializeComponent();
        }

        private void txt_LocationSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }

            if (string.IsNullOrEmpty(cmb_PartNumber.Text))
            {
                areaMsg.Text = "请先选择物料";
                cmb_PartNumber.Focus();
                return;
            }

            if (IsDateTime(txt_DateCode.Text) == false)
            {
                areaMsg.Text = "生产日期格式错误（例:20190501）";
                txt_DateCode.Focus();
                return;
            }

            _ToLocation = txt_ToLocation.Text;
            _DateCode = txt_DateCode.Text;

            string storageSN;
            string aresSN;
            try
            {
                var snArray = _ToLocation.Split('#');

                storageSN = snArray[0];
                aresSN = snArray[0] + '#' + snArray[1];

                if (!string.IsNullOrEmpty(_StorageSN) && !_StorageSN.Equals(storageSN))
                {
                    areaMsg.Text = "上架仓库" + _StorageSN + "与扫描的仓库" + storageSN + "不一致！";
                    return;
                }

                txt_ToLocation.Text = snArray[1] + '#' + snArray[2];
            }
            catch
            {
                areaMsg.Text = "库位" + _ToLocation + "格式不正确，请重新输入!";
                txt_ToLocation.Text = "";
                return;
            }

            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("本次操作的上架库位：" + txt_ToLocation.Text + ", 请确认！", "上架确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

            if (dr == DialogResult.OK)
            {
                var qty = Convert.ToDecimal(txt_Qty.Text);
                var ret = Query("C010999999999999", _PartNumber, Utils.uContext.UserNamek__BackingField, _FromLocation, aresSN, _ToLocation, _DateCode, qty);

                if (ret.Equals("OK"))
                {
                    areaMsg.Text = cmb_PartNumber.Text + "上架成功!";
                    txt_ToLocation.Enabled = false;
                }
                else
                {
                    areaMsg.Text = cmb_PartNumber.Text + "上架失败!\r\n" + ret;

                }
            }
        }


        string _StorageSN;
        string _FromLocation;
        string _PartNumber;
        string _DateCode;
        string _Version;
        string _Guid;
        decimal _Qty;
        string _ToLocation;

        private void FrmTranseferIn_Load(object sender, EventArgs e)
        {
            FrmReset();
        }

        /// <summary>
        /// 下架库位扫描
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_FromLocation_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }

            try
            {
                var snArray = txt_FromLocation.Text.Split('#');
                _StorageSN = snArray[0];
                //var aresSN = snArray[0] + '#' + snArray[1];
                _FromLocation = txt_FromLocation.Text;
                txt_FromLocation.Text = snArray[1] + "#" + snArray[2];
            }
            catch
            {
                areaMsg.Text = "库位格式不正确，请确认！";
                txt_FromLocation.Text = "";
                txt_FromLocation.Focus();
                return;
            }


            //库存检查
            string sql = string.Format(@"SELECT * FROM dbo.wms_T_Inventory WHERE Location_SN='{0}' ORDER BY PartNumber,DateCode,Qty", _FromLocation);
            var dtIvt = Utils.NMS.GetDataTable(sql);

            if (dtIvt.Rows.Count == 0)
            {
                areaMsg.Text = "下架仓库中没有库存，请确认！";
                txt_FromLocation.Text = "";
                txt_FromLocation.Focus();
                return;
            }

            areaInfo.Text = "当前仓库：" + _StorageSN + "\r\n当前物料：\r\n库存数量：";

            //物料绑定
            cmb_PartNumber.DisplayMember = "PartNumber";
            cmb_PartNumber.ValueMember = "Guid";
            cmb_PartNumber.DataSource = dtIvt;

            cmb_PartNumber.Focus();

            areaMsg.Text = "请选择物料";
        }

        /// <summary>
        /// 物料选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmb_PartNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmb_PartNumber.SelectedValue != null)
            {
                //锁定库位
                this.txt_FromLocation.Enabled = false;

                _Guid = this.cmb_PartNumber.SelectedValue.ToString();
                string sql = string.Format(@"SELECT * FROM dbo.wms_T_Inventory WHERE Guid='{0}'", _Guid);
                var dtIvt = Utils.NMS.GetDataTable(sql);

                if (dtIvt.Rows.Count == 0)
                {
                    areaMsg.Text = "当前物料库存已不存在，请确认！";
                }

                _PartNumber = dtIvt.Rows[0]["PartNumber"].ToString(); ;
                _Version = dtIvt.Rows[0]["Version"].ToString(); ;
                _DateCode = dtIvt.Rows[0]["DateCode"].ToString();


                if (string.IsNullOrEmpty(_DateCode) == true)
                {
                    txt_DateCode.Text = "";
                    txt_DateCode.Enabled = true;
                }
                else
                {
                    txt_DateCode.Text = _DateCode;
                    txt_DateCode.Enabled = false;
                }

                areaInfo.Text = "当前仓库：" + _StorageSN +
                        "\r\n当前物料：" + dtIvt.Rows[0]["PartNumber"].ToString() +
                        "\r\n库存数量：" + dtIvt.Rows[0]["Qty"].ToString();
                _Qty = Convert.ToDecimal(dtIvt.Rows[0]["Qty"].ToString());
            }
        }

        /// <summary>
        /// 数量输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_Qty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }

            decimal qty = 0;
            try
            {
                qty = Convert.ToDecimal(txt_Qty.Text);
            }
            catch
            {
                areaMsg.Text = "请输入正确的数字！";
                txt_Qty.Text = "";
                return;
            }

            if (qty == 0)
            {
                areaMsg.Text = "数量不能为0！";
                txt_Qty.Text = "";
                return;
            }
            if (qty > _Qty)
            {
                areaMsg.Text = "数量不能大于库存数量！";
                txt_Qty.Text = "";
                return;
            }

            cmb_PartNumber.Enabled = false;
            if (txt_DateCode.Enabled)
            {
                txt_DateCode.Focus();
            }
            else
            {
                txt_ToLocation.Focus();
            }
        }

        /// <summary>
        /// 生产日期录入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtDateCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (IsDateTime(txt_DateCode.Text) == false)
                {
                    areaMsg.Text = "生产日期格式错误（例:20190501）";
                    return;
                }
                _DateCode = txt_DateCode.Text;
                this.txt_ToLocation.Focus();
            }
        }

        /// <summary>
        /// 重置按钮按下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Reset_Click(object sender, EventArgs e)
        {
            var ret = MessageBox.Show("是否重置画面", "提示", MessageBoxButtons.OKCancel,
                                                                        MessageBoxIcon.Question,
                                                                        MessageBoxDefaultButton.Button1);
            if (ret == DialogResult.OK)
            {
                FrmReset();
            }
        }

        #region 内部方法
        private void FrmReset()
        {
            txt_FromLocation.Enabled = true;
            cmb_PartNumber.Enabled = true;
            txt_Qty.Enabled = true;
            txt_DateCode.Enabled = true;
            txt_ToLocation.Enabled = true;

            areaMsg.Text = "";
            areaInfo.Text = "";

            txt_FromLocation.Text = "";
            cmb_PartNumber.DataSource = null;
            txt_Qty.Text = "";
            txt_DateCode.Text = "";
            txt_ToLocation.Text = "";

            _StorageSN = "";
            _FromLocation = "";
            _PartNumber = "";
            _DateCode = "";
            _Version = "";
            _Guid = "";
            _Qty = 0;
            _ToLocation = "";

        }

        /// <summary>
        /// 判断时间格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private bool IsDateTime(string str)
        {
            System.IFormatProvider format = new System.Globalization.CultureInfo("zh-CN", true);
            try
            {
                DateTime.ParseExact(str, "yyyyMMdd", format);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private string Query(string inBillNo, string inPartNumber, string inUserName,
                                string inOLocationSN, string inIArea, string inILocationSN, string inDateCode, decimal inQty)
        {
            string sqlcmd = string.Format(@"begin 
                                            DECLARE @ret varchar(50);
                                            exec PDA_Move_query N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}',{7},@ret output;
                                            SELECT @ret 
                                            end", inBillNo, inPartNumber, inUserName, inOLocationSN, inIArea, inILocationSN, inDateCode, inQty);
            var result = Utils.NMS.GetDataTable(sqlcmd);
            return result.Rows[0][0].ToString();
        }
        #endregion

        //END
    }
}